import { Provide } from '@midwayjs/core';
import { OrdersProductsMap } from '../entity/OrdersProductsMap';
import { InjectEntityModel } from '@midwayjs/orm';
import { Equal, Not, Repository } from 'typeorm';
import { BaseService } from './base';
import { TeamLeaderServiceFee } from '../entity/TeamLeaderServiceFee';
import { ExpertCommission } from '../entity/ExpertCommission';

@Provide()
export class OrdersProductsMapService extends BaseService<OrdersProductsMap> {
  @InjectEntityModel(OrdersProductsMap)
  entity: Repository<OrdersProductsMap>;

  async list({ data, ...otherData }) {
    return await super.list({
      data: { ...data, status: Not(Equal('已关闭')) },
      otherData: { ...otherData },
    });
  }

  async add(data) {
    return await super.add(data);
  }

  async update(data) {
    return await super.update(data);
  }

  async upsert(data) {
    return await super.upsert(data, { conflictPaths: ['id'] });
  }

  async all(data: any = {}) {
    return await this.entity
      .createQueryBuilder('ordersProductsMap')
      .where('ordersProductsMap.data_date = :data_date', {
        data_date: data.data_date,
      })
      .where('ordersProductsMap.store_name = :store_name', {
        store_name: data.store_name,
      })
      .where('ordersProductsMap.status != "已关闭"')
      .leftJoinAndMapOne(
        'ordersProductsMap.teamLeaderServiceFee',
        TeamLeaderServiceFee,
        'teamLeaderServiceFee',
        'teamLeaderServiceFee.product_id = ordersProductsMap.product_id'
      )
      .leftJoinAndMapOne(
        'ordersProductsMap.expertCommission',
        ExpertCommission,
        'expertCommission',
        'expertCommission.product_id = ordersProductsMap.product_id'
      )
      .getMany();
  }
}
